package com.songtech.server.frame.service;

import com.songtech.server.constant.KeysConstant;
import com.songtech.server.constant.TcpServer;
import com.songtech.server.entry.BaseProtocal;
import com.songtech.server.entry.ConfirmProtocal;
import com.songtech.server.frame.BaseServiceRegister;
import com.songtech.server.frame.dao.mapper.TerminalSettingHistoryMapper;
import com.songtech.server.frame.dao.mapper.TerminalSettingMapper;
import com.songtech.server.frame.route.annotation.Allot;
import com.songtech.server.frame.service.setting.ISetting;
import com.songtech.server.task.RedisLock;
import com.songtech.server.utils.FormatDateUtils;
import com.songtech.server.utils.GetKeysUtils;
import com.songtech.web.entry.Setting;
import com.songtech.web.entry.SysPosTerminalHistory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * Create By YINN on 2018/4/7 2:28
 * Description : 测试service，各service通过@Allot(cmd = "命令值")分辨各协议从而进入不同service,
 * 所有业务service都需要实现BaseService接口!!!
 */

@Allot(cmd = "V4", beanClass = ConfirmProtocal.class)
@Service
public class ConfirmServiceImpl extends PositionServerServiceImpl implements BaseService {

    private final static int STATUS = 1;

    private final static String LOCK_KEY = KeysConstant.LOCK_KEY;

    @Autowired
    private TerminalSettingMapper terminalSettingMapper;

    @Autowired
    private TerminalSettingHistoryMapper terminalSettingHistoryMapper;

    @Override
//    @Transactional
    public void invoke(BaseProtocal baseProtocal) {

        super.invoke(baseProtocal);

        //获取确认协议实体
        ConfirmProtocal protocal = (ConfirmProtocal) baseProtocal;

        //获取确认命令与imei
        String confirmCmd = protocal.getConfirmCmd();
        String imei = protocal.getImei();


        String lockObjKey = GetKeysUtils.combineAnyKeys(confirmCmd, protocal.getImei());

        String msg = ((String) RedisLock.getLockedEntry(LOCK_KEY, lockObjKey));

        if (StringUtils.isBlank(msg)){
            return;
        }

        try{

        String[] targets = msg.replace("*","").replace("#","").split(",");

        //执行查询
        int count = terminalSettingMapper.getSettingCount(imei);

        ISetting iSetting = BaseServiceRegister.getISetting(confirmCmd);

        //判断是否需要存储入设置表中
        if (iSetting != null){
            Setting setting = new Setting();
            setting.setImei(imei);
            setting.setStatus(STATUS);

            setting = iSetting.val(setting,targets);

            //存储入库
            save(setting,count);

            //记录历史
            SysPosTerminalHistory history = new SysPosTerminalHistory();
            history.setImei(imei);
            history.setSender(1);
            history.setStatus(1);
            history.setCmdType(confirmCmd);
            history.setTerminalSendTime(FormatDateUtils.LocalTimeParseToDate(FormatDateUtils.parseToLocalTime(targets[3])));
            history.setTerminalReplyTime(protocal.getRecordTime());

            saveHistory(history);
        }

        }catch (Exception e){

            e.printStackTrace();

        }finally {

            //移除对象锁
            RedisLock.removeLock(LOCK_KEY, lockObjKey);

            System.out.println("移除对象锁成功!");

        }

    }


    /**
     * Created by YINN on 2018/4/23 12:42.
     * @Description : 保存方法
     * @param setting 实体类
     * @param count 根据imei 查询出来的条数) 判断insert or update
     * @Result :
     */
    private int save(Setting setting, int count) {

        setting.setUpdateTime(new Date());
        setting.setUpdateUser(TcpServer.TCP_SERVER_USERNAME);

        if (count > 0) {

            System.out.println("update");

            return terminalSettingMapper.updateSetting(setting);

        } else {

            setting.setCreateTime(new Date());
            setting.setCreateUser(TcpServer.TCP_SERVER_USERNAME);

            System.out.println("add");

            return terminalSettingMapper.addSetting(setting);

        }

    }


    private int saveHistory(SysPosTerminalHistory history){

        return terminalSettingHistoryMapper.addTerminalSettingHistory(history);

    }
}
